package com.wh.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    SqlSession sqlSession = factory.openSession(true);

    static {

        try {
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //SqlSessionFactory表示会话工厂，需要加载Mybatis的主配置文件
            factory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static SqlSession getSqlSession() {
        return getSqlSession(false);
    }

    public static SqlSession getSqlSession(boolean isAutoCommit) {
        SqlSession sqlSession = local.get();
        // SqlSession 表示MyBatis会话，就是与数据库的连接
        if (sqlSession == null) {
            sqlSession = factory.openSession(isAutoCommit);
            local.set(sqlSession);
        }
        return sqlSession;
    }

    public static <T extends Object> T getMapper(Class<T> c) {
        return getMapper(c,true);
    }
    public static <T extends Object> T getMapper(Class<T> c,boolean isAutoCommit) {
        SqlSession sqlSession = getSqlSession(isAutoCommit);
        return sqlSession.getMapper(c);
    }

}
